var request = require('request');
let mysql = require('mysql');
let db = require('../libs/db');
let sql = require('../sql/sql');
let moment = require('moment');
let data = require('../libs/data');
var shortId = require('shortid');
var utils = require('../libs/utils');
var client = require('redis').createClient();
var jwt = require("jsonwebtoken");
var Manager = db.Manager;
var declare = db.declare;
var Ac = db.Ac;
client.on('error', function (err) {
    console.log('Error ' + err);
});

let Dealer = db.Dealer;
let Code = db.code;
let Userwx = db.Userwx;
function formatDate(rows) {
    return rows.map(row => {
        let date = moment(row.create_time).format('YYYY-MM-DD');
        let obj = {};

        switch (row.role) {
            case 1:
                obj.role = '普通用户';
                break;
            case 2:
                obj.role = '管理员';
                break;
            case 100:
                obj.role = '超级管理员';
        }

        delete row.password;

        return Object.assign({}, row, {create_time: date}, obj);
    });
}

function getWXUserInfoFun(token, openid) {
    return new Promise(function (resolve, reject) {
        request({
            url: 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' + token + '&openid=' + openid + '&lang=zh_CN',
            method: "POST",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
        }, function (error, response, body) {
            console.log(body);
            if (error) {
                reject(error);
            } else {
                resolve(JSON.parse(body).nickname);
            }
        });
    });
}

module.exports = {
    // 注册添加用户
    register (req, res) {
        var phone = req.body.phone;
        var smscode = req.body.smscode;
        var username = req.body.username;
        var userid = shortId.generate();
        var code = req.body.codeid;
        var dealerData = {
            phone: phone,
            username: username,
            shopname: req.body.shopname,
            prov: req.body.prov,
            city: req.body.city,
            area: req.body.area,
            address: req.body.address,
            code: code,
            idnumber: req.body.idnumber,
            userid: userid,
            fgs: req.body.fgs,
            bsc: req.body.bsc,
        };
        // client.get('sms_' + phone, function (err, object) {
        //     if (err || (smscode != object)) {
        //         data.code = '102';
        //         data.msg = '验证码不正确';
        //         data.data = '';
        //         res.status(200).send(JSON.stringify(data));
        //     } else {
        //
        //
        //     }
        // });
        Code.findOne({
            where: {
                code: code
            }
        }).then(function (result) {
            if (result) {
                Dealer.findOne({
                    where: {
                        code: code
                    }
                }).then(function (result) {
                    if (result) {
                        data.code = '101';
                        data.msg = '注册码已注册';
                        data.data = '';
                        res.status(200).send(JSON.stringify(data));
                    } else {
                        db.sequelize.transaction(function (t) {

                            return Dealer.create(dealerData, {
                                transaction: t
                            })
                        }).then(function (result) {

                            data.code = '200';
                            data.msg = '添加数据成功';
                            data.data = {phone: phone, username: username, userid: userid};
                            var token = jwt.sign(JSON.stringify(data.data), "secret");
                            data.token = token;
                            res.status(200).send(JSON.stringify(data));
                        }).catch(function (err) {
                            console.log(err.parent.errno);
                            console.log(err.parent.sqlState);
                            if (err.parent && (err.parent.sqlState = '23000')) {
                                data.code = '101';
                                data.msg = '手机号码已存在';
                                data.data = '';
                                res.status(200).send(JSON.stringify(data));
                            } else {
                                data.code = '101';
                                data.msg = '添加数据失败';
                                data.data = '';
                                res.status(200).send(JSON.stringify(data));
                            }
                        });
                    }
                });
            } else {
                data.code = '101';
                data.msg = '注册码不存在';
                data.data = '';
                res.status(200).send(JSON.stringify(data));
            }
        });
    },
    // 登录
    login (req, res) {
        var phone = req.body.phone;
        var smscode = req.body.smscode;
        var loginType = req.body.loginType;

        client.get('sms_' + phone, function (err, object) {
            if (err || (smscode != object)) {
                data.code = '102';
                data.msg = '验证码不正确';
                res.status(200).send(JSON.stringify(data));
            } else {
                return Dealer.findOne({
                    where: {
                        phone: phone
                    },
                    attributes: ['phone', 'username', 'userid']
                }).then(function (result) {
                    var result = JSON.parse(JSON.stringify(result));
                    if (result) {
                        data.code = '200';
                        data.msg = '查询数据成功';
                        data.data = JSON.stringify(result);
                        var token = jwt.sign(data.data, "secret");
                        data.token = token;
                        res.status(200).send(JSON.stringify(data));
                    } else {
                        data.code = '103';
                        data.msg = '账号不存在';
                        data.data = '';
                        res.status(200).send(JSON.stringify(data));
                    }
                }).catch(function (err) {
                    data.code = '101';
                    data.msg = '查询数据失败';
                    data.data = '';
                    res.status(200).send(JSON.stringify(data));
                });
            }
        });
    },
    smsSend: function (req, res) {
        var phone = req.body.phone;
        var smscode = utils.randomWord(false, 6);
        var smsData = {
            "account": "dh56451",
            "password": "9fae6285686bee935da29cc8a18dd290",
            "msgid": "",
            "phones": phone,
            "content": "欢迎您参加景芝杯-民间品酒师发现之旅活动，您的验证码是:" + smscode + '。请于2分钟内在网页输入。',
            "sign": "【极优佳】",
            "subcode": "",
            "sendtime": ""
        };
        request({
            url: "http://www.dh3t.com/json/sms/Submit",
            method: "POST",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
                "Content-Length": smsData.length
            },
            body: JSON.stringify(smsData)
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                data.code = '200';
                data.msg = '发送短信成功';
                data.smscode = smscode;
                data.data = '';
                client.set('sms_' + phone, smscode, function (err) {
                    console.log(err)
                });
                client.expire('sms_' + phone, 120);
            } else {
                data.code = '101';
                data.msg = '发送短信失败';
                data.data = '';
            }
            res.status(200).send(JSON.stringify(data));
        });
    },
    getWXuserinfo: function (req, res) {
        var phone = req.body.phone;
        var sql = 'select * from jyj_user_wx';
        request({
            url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx3b8a43a94bdb7f4e&secret=a6de5dd06aa29b7dea123551e9e1efc7',
            method: "POST",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            },
        }, function (error, response, body) {
            console.log(body);
            let token = JSON.parse(body).access_token;
            if (!error) {
                db.sequelize.query(sql, {
                    type: db.sequelize.QueryTypes.SELECT
                }).then(function (result) {
                    var datas = result;
                    (async () => {
                        for (var i = 0; i < datas.length; i++) {
                            var openid = datas[i].openid;
                            var wxid = datas[i].id;
                            console.log(wxid);
                            var nickname = await getWXUserInfoFun(token, openid);
                            if (nickname) {
                                var param = {
                                    nick: nickname,
                                }
                                let userwx = await Userwx.findOne({
                                    where: {
                                        openid: openid
                                    },
                                });
                                let userwx_update = await userwx.update(param);
                            }
                        }
                    })();
                }).catch(function (err) {
                    data.code = '101';
                    data.msg = '查询数据失败';
                    res.status(200).send(JSON.stringify(data));
                });
            }
        });
    },
    dscreen(req, res){
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        console.log(userData);
        return Dealer.findOne({
            where: {
                phone: userData.phone,
            },
            attributes: ['id', 'phone']
        }).then(function (result) {
            if (result) {
                var data1Sql1 = 'SELECT a.acid,a.name,a.address,a.activityArea,a.lunci,date_format(a.ctime,"%Y-%m-%d") time from jyj_ac a where a.tag = "3" order by a.id desc';
                db.sequelize.query(data1Sql1, {
                    type: db.sequelize.QueryTypes.SELECT
                }).then(function (dataResult1) {
                    console.log(dataResult1);
                    data.code = '200';
                    data.msg = '查询数据成功';
                    data.data = dataResult1;
                    data.token = token;
                    res.status(200).send(JSON.stringify(data));
                }).catch(function (err) {
                    data.code = '101';
                    data.msg = '查询数据失败';
                    data.data = '';
                    res.status(200).send(JSON.stringify(data));
                });
            } else {
                data.code = '103';
                data.msg = '账号或密码错误';
                data.data = '';
                res.status(200).send(JSON.stringify(data));
            }
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            data.data = '';
            res.status(200).send(JSON.stringify(data));
        });
    },

    /*--------------------------------------------申报活动------------------------------------------------------------*/
    declare(req, res){
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        console.log(userData);
        return Dealer.findOne({
            where: {
                phone: userData.phone,
            },
            attributes: ['id', 'phone']
        }).then(function (result) {
            var declareData = {
                company: req.body.company,
                office: req.body.office,
                city: req.body.city,
                host: req.body.host,
                store: req.body.store,
                hotel: req.body.hotel,
                jbtime: req.body.jbtime,
                hdtime: req.body.hdtime,
                qunti: req.body.qunti,
                userid: userData.userid
            };

            db.sequelize.transaction(function (t) {
                return declare.create(declareData, {
                    transaction: t
                })
            }).then(function (result) {
                console.log(result);
                data.code = '200';
                data.msg = '添加数据成功';
                var token = jwt.sign(JSON.stringify(data.data), "secret");
                data.token = token;
                res.status(200).send(JSON.stringify(data));
            })
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            data.data = '';
            res.status(200).send(JSON.stringify(data));
        });
    },
    findDeclareList(req, res){
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        var sql = 'select a.acid,a.name,a.address,a.number,a.lunci,a.activityArea,DATE_FORMAT(a.ctime,"%Y-%m-%d") times from jyj_ac a where a.userid = :userid and DATE_FORMAT(a.ctime, "%Y-%m-%d") = DATE_FORMAT(NOW(),"%Y-%m-%d") and a.tag=:tag order by id';
        db.sequelize.query(sql, {
            replacements: {userid: userData.userid},
            type: db.sequelize.QueryTypes.SELECT
        }).then(function (result) {
            console.log(result.length);
            data.code = '200';
            data.msg = '查询数据成功';
            data.data = result;
            res.status(200).send(JSON.stringify(data));
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            res.status(200).send(JSON.stringify(data));
        });

    },
    ac_delete(req,res){
        var acid = req.body.acid;
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        return Ac.destroy({
            where: {
                userid: userData.userid,
                acid: acid,
            },
        }).then(function (result) {
            data.code = '200';
            data.msg = '删除数据成功';
            data.data = result;
            res.status(200).send(JSON.stringify(data));
        }).catch(function (err) {
            data.code = '101';
            data.msg = '删除数据失败';
            data.data = '';
            res.status(200).send(JSON.stringify(data));
        });
    },
    findUser(req,res){
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        var sql = 'SELECT a.*, b.title fgstitle, c.title bsctitle FROM jyj_dealer a LEFT JOIN jyj_area b ON a.fgs = b.id LEFT JOIN jyj_area c ON a.bsc = c.id WHERE a.userid = :userid';
        db.sequelize.query(sql, {
            replacements: {userid: userData.userid},
            type: db.sequelize.QueryTypes.SELECT
        }).then(function (result) {
            console.log(result.length);
            data.code = '200';
            data.msg = '查询数据成功';
            data.data = result[0];
            res.status(200).send(JSON.stringify(data));
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            res.status(200).send(JSON.stringify(data));
        });
    },
    findArea(req,res){
        var areaid = req.body.area;
        var sql = 'select * from jyj_area a where a.pid = :areaid';
        db.sequelize.query(sql, {
            replacements: {areaid: areaid},
            type: db.sequelize.QueryTypes.SELECT
        }).then(function (result) {
            console.log(result.length);
            data.code = '200';
            data.msg = '查询数据成功';
            data.data = result;
            res.status(200).send(JSON.stringify(data));
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            res.status(200).send(JSON.stringify(data));
        });
    }

};